<template>
  <div class="common-layout">
    <el-container>
    <el-header style="border-style: groove;border-width: 2px;height: 60px;margin-bottom: 15px;">
        <el-form :inline="true" :model="can" class="demo-form-inline" style="margin-top: 12px;">
            <el-form-item label="状态">
            <el-select
                v-model="can.InventoryStatus"
                placeholder="状态"
                clearable
            >
                <el-option label="待审核" :value="3" />
                <el-option label="进行中" :value="1" />
                <el-option label="已完成" :value="2" />
            </el-select>
            </el-form-item>
            <el-form-item>
            <el-button type="primary" @click="getInventoryList()">查询</el-button>
            </el-form-item>
        </el-form>
    </el-header>
    <el-main style="border-style: groove;border-width: 2px;height: 630px;">
        <div style="margin-bottom: 15px;">
            <el-button type="success" plain @click="addTask()">新增</el-button>
            <!-- <el-button type="primary" plain @click="batchOperation" :disabled="selectedIds.length === 0">
              批量操作 ({{ selectedIds.length }})
            </el-button>
            <el-button type="info" plain @click="clearSelection">清空选择</el-button>
            <el-button type="warning" plain @click="selectAll">全选</el-button>
            <el-button type="danger" plain @click="toggleSelection">反选</el-button> -->
        </div>


          <el-table ref="tableRef" :data="tableData" style="width: 100%" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" />
          <el-table-column fixed type="index" label="序号" />
          <el-table-column  prop="inventoryNnumber" label="单号" width="150" >
            <template v-slot="scoped">
              <el-button  v-if="scoped.row.isHaveGoods==true" link type="primary" size="small" @click="details(scoped.row.id)">{{scoped.row.inventoryNnumber}}</el-button>
              <span v-if="scoped.row.isHaveGoods==false">{{scoped.row.inventoryNnumber}}</span>
            </template>
          </el-table-column>
          <el-table-column prop="storeName" label="所属仓库"/>
          <el-table-column prop="inventoryStatus" label="状态">
            <template v-slot="scoped">
              <span v-if="scoped.row.inventoryStatus==1">进行中</span>
              <span v-if="scoped.row.inventoryStatus==2">已完成</span>
              <span v-if="scoped.row.inventoryStatus==3">待审核</span>
            </template>
          </el-table-column>
          <el-table-column prop="inventoryType" label="盘点类型" >
            <template v-slot="scoped">
              <span v-if="scoped.row.inventoryType==1">全面盘点</span>
              <span v-if="scoped.row.inventoryType==2">部分盘点</span>
            </template>
          </el-table-column>
          <el-table-column prop="inventoryRange" label="盘点范围" >
            <template v-slot="scoped">
              <span v-if="scoped.row.inventoryType==1">仓库区域</span>
              <span v-if="scoped.row.inventoryType==2">货品类别</span>
            </template>
          </el-table-column>
          <el-table-column prop="inventoryStartTime" label="盘点开始">
            <template v-slot="scoped">
              <span>{{moment(scoped.row.inventoryStartTime).format("YYYY-MM-DD")}}</span>
            </template>
          </el-table-column>
          <el-table-column prop="inventoryEndTime" label="盘点结束">
              <template v-slot="scoped">
              <span>{{moment(scoped.row.inventoryEndTime).format("YYYY-MM-DD")}}</span>
            </template>
          </el-table-column>
          <el-table-column prop="attnName" label="经办人"/>
          <el-table-column prop="createUserName" label="制单人"/>
          <el-table-column prop="note" label="备注"/>
          <el-table-column fixed="right" label="操作" min-width="180">
            <template #default="scoped">
              <el-button v-if="scoped.row.isHaveGoods==true" link type="success" size="small" @click="details(scoped.row.id)">
                查看详情
              </el-button>
              <el-button v-if="scoped.row.isHaveGoods==false" link type="primary" size="small" @click="editTask(scoped.row.id)">
                配置盘点货品
              </el-button>
              
            </template>
          </el-table-column>
        </el-table>

         <div class="demo-pagination-block" style="margin-top: 20px;">
            <el-pagination
            v-model:current-page="page.PageIndex"
            v-model:page-size="page.PageSize"
            :page-sizes="[15, 20, 30, 50]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="page.listcount"
            />
        </div>
    </el-main>
    </el-container>
  </div>
</template>
<script lang="ts" setup>
import { inventoryRead } from '@/Helper/axiosSetting'
import moment from 'moment'
import { onMounted, reactive, ref, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'

import {useCounterStore} from '@/stores/counter'
const router=useRouter()
const user=useCounterStore();

onMounted(()=>{
  getInventoryList()
})

const can = reactive({
  InventoryStatus: null,
})
const page=reactive({
  PageIndex:1,
  PageSize:15,
  listcount:0
})
watch(page,()=>{
    getInventoryList()
},{deep:true})


const tableData=ref([])
// 选中的行数据和ID列表
const selectedRows = ref<any[]>([])
const selectedIds = ref<number[]>([])
const tableRef = ref()

const getInventoryList=()=>{
  inventoryRead.get("/api/InventoryRead/InventoryTaskList",{params:{
    PageIndex:page.PageIndex,
    PageSize:page.PageSize,
    InventoryStatus:can.InventoryStatus,
    UserId:user.UserInfo.Uid
  }}).then(res=>{
    tableData.value=res.data.data.list
    page.listcount=res.data.data.count
    // 清空之前的选择状态
    selectedRows.value = []
    selectedIds.value = []
  })
}


//跳转添加
const addTask=()=>{
  router.push({
    path:'/AddInventory'
  })
}
//跳转编辑
const editTask=(id:number)=>{
  router.push({
    path:'/AddInventory',
    query:{id:id}
  })
}

// 处理表格选择变化
const handleSelectionChange = (selection: any[]) => {
  selectedRows.value = selection
  selectedIds.value = selection.map(row => row.id)
  console.log('选中的行数据:', selectedRows.value)
  console.log('选中的ID列表:', selectedIds.value)
}

// 批量操作
const batchOperation = () => {
  if (selectedIds.value.length === 0) {
    ElMessage.warning('请先选择要操作的数据')
    return
  }
  
  ElMessageBox.confirm(
    `确定要对选中的 ${selectedIds.value.length} 条数据进行批量操作吗？`,
    '批量操作确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    // 这里执行批量操作逻辑
    console.log('执行批量操作，选中的ID:', selectedIds.value)
    
    // 示例：批量删除或批量更新状态
    batchDelete(selectedIds.value)
    
    ElMessage.success(`批量操作成功，共处理 ${selectedIds.value.length} 条数据`)
  }).catch(() => {
    ElMessage.info('已取消批量操作')
  })
}

// 批量删除/更新示例
const batchDelete = (ids: number[]) => {
  // 这里可以调用后端API进行批量操作
  // inventoryWrite.post('/api/InventoryWrite/BatchDelete', { ids })
  console.log('批量删除ID:', ids)
  
  // 操作完成后刷新列表
  getInventoryList()
  clearSelection()
}

// 清空选择
const clearSelection = () => {
  if (tableRef.value) {
    tableRef.value.clearSelection()
  }
  selectedRows.value = []
  selectedIds.value = []
  ElMessage.info('已清空选择')
}

// 选择全部
const selectAll = () => {
  if (tableRef.value) {
    tableRef.value.toggleAllSelection()
  }
}

// 反选
const toggleSelection = () => {
  if (tableRef.value && tableData.value) {
    tableData.value.forEach(row => {
      tableRef.value.toggleRowSelection(row)
    })
  }
}

//查看盘点详情
const details=(id:number)=>{
  router.push({
    path:'/InventoryDetail',
    query:{id:id}
  })
}

//删除盘点任务
const deleteTask = async (id: number) => {
  try {
    await ElMessageBox.confirm('确定要删除这个盘点任务吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    
    // 这里调用删除API
    ElMessage.success('删除成功')
    getInventoryList() // 刷新列表
  } catch {
    ElMessage.info('已取消删除')
  }
}


</script>





<style>
.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}
</style>